<?php

// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org 
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------

namespace app\admin\traits;

use app\admin\model\publicuse\PublicUse;
use EasyAdmin\annotation\NodeAnotation;
use EasyAdmin\tool\CommonTool;
use jianyan\excel\Excel;
use think\facade\Cache;
use think\facade\Db;

/**
 * 后台CURD复用
 * Trait Curd
 * @package app\admin\traits
 */
trait Curd
{


    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        $param = request()->param();
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames([],$this->AllData['field']??[]);
            if(isset($this->AllData['is_page'])&&$this->AllData['is_page']==0){
                $limit = 10000;
            }
            $where = PublicUse::getParameter($where);
            Cache::set('where'.__CLASS__,$where);
            $with = [];
            if(isset($this->AllData['field'])&&$this->AllData['field']){
                foreach ($this->AllData['field'] as $value){
                    if($value['show']==1){
                        if(in_array($value['formtype'],['lradio','lselect','aselect','aselectgroup','selectgroup'])){
                            $with[] = 'get'.str_replace('_','',$value['field']).'field';
                        }
                    }
                }
            }
            if(empty($with)){
                $count = $this->model
                    ->where($where)
                    ->count();
            }else{
                $count = $this->model
                    ->with($with)
                    ->where($where)
                    ->count();
            }
            if(empty($with)){
                try{
                    $list = $this->model
                        ->where($where)
                        ->page($page, $limit)
                        ->order($this->sort)
                        ->select();
                }catch (\Exception $e){
                    $list = $this->model
                        ->where($where)
                        ->page($page, $limit)
//                ->order($this->sort)
                        ->select();
                }
            }else{
                try{
                    $list = $this->model
                        ->with($with)
                        ->where($where)
                        ->page($page, $limit)
                        ->order($this->sort)
                        ->select();
                }catch (\Exception $e){
                    $list = $this->model
                        ->with($with)
                        ->where($where)
                        ->page($page, $limit)
//                ->order($this->sort)
                        ->select();
                }
            }
            $list = PublicUse::objctToModelAndField($list,$this->AllData['field']??[]);
//            dump($list);exit;
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $parameter = '';
        $fi = $this->model->getPk();
        if(!empty($param['field'])&&!empty($param[$fi])){
            $parameter = "?{$param['field']}={$param[$fi]}";
        }
        $newwhere = $this->request->get();
        foreach ($newwhere as $key=>$value){
            if($key!==$fi&&$key!=='field'){
                if(strpos($parameter,'?')===false){
                    $parameter .= "?{$key}={$value}";
                }else{
                    $parameter .= "&{$key}={$value}";
                }
            }
        }
        $this->assign('parameter',$parameter);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        $data = request()->param();
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
//            return $this->error('保存失败2',$post);
            if(isset($this->AllData['field'])&&!empty($this->AllData['field'])){
                $post = PublicUse::Conversion($post,$this->AllData['field']);
            }
//            dump($post);exit;
            try {
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败:'.$e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        if(isset($this->AllData['field'])){
            if($this->AllData['field']){
                $this->AllData['field'] = PublicUse::FieldGetLianJie($this->AllData['field']);
            }
            if($this->AllData['tabletype']=='tree'){
                if(isset($this->AllData['field']['pid']['option'])&&$this->AllData['field']['pid']['option']){
                    $this->AllData['field']['pid']['option'] = PublicUse::getPidMenuList($this->AllData['field']['pid']['option']);
                }
            }
            $this->assign('alldata',$this->AllData);
        }
        if(isset($data['field'])&&isset($data['id'])&&$data['field']&&$data['id']){
            $data[$data['field']] = $data['id'];
            unset($data['field']);
            unset($data['id']);
        }
        $this->assign('row',$data);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit()
    {
        $id = request()->param($this->model->getPk());
//        $data = request()->param();
//        dump($data);exit;
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            if(isset($this->AllData['field'])&&!empty($this->AllData['field'])){
                $post = PublicUse::Conversion($post,$this->AllData['field']);
            }
            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        if(isset($this->AllData['field'])){
            if($this->AllData['field']){
                $this->AllData['field'] = PublicUse::FieldGetLianJie($this->AllData['field'],$row);
            }
            if($this->AllData['tabletype']=='tree'){
                if(isset($this->AllData['field']['pid']['option'])&&$this->AllData['field']['pid']['option']){
                    $this->AllData['field']['pid']['option'] = PublicUse::getPidMenuList($this->AllData['field']['pid']['option']);
                }
            }
            $this->assign('alldata',$this->AllData);
        }
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="查看详情")
     */
    public function details(){
        $id = request()->param($this->model->getPk());
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
//            return $this->error('保存失败',$post);
            if(isset($this->AllData['field'])&&!empty($this->AllData['field'])){
                $post = PublicUse::Conversion($post,$this->AllData['field']);
            }
            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        if(isset($this->AllData['field'])){
            if($this->AllData['field']){
                $this->AllData['field'] = PublicUse::FieldGetLianJie($this->AllData['field'],$row);
            }
            if($this->AllData['tabletype']=='tree'){
                if(isset($this->AllData['field']['pid']['option'])&&$this->AllData['field']['pid']['option']){
                    $this->AllData['field']['pid']['option'] = PublicUse::getPidMenuList($this->AllData['field']['pid']['option']);
                }
            }
            $this->assign('alldata',$this->AllData);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="删除")
     */
    public function delete()
    {
        $data = request()->param();
        $field = $this->model->getPk();
        if(!$field){
            $field = 'id';
        }
        if(!isset($data[$field])){
            return $this->error('请传入主键');
        }
        $row = $this->model->whereIn($field, $data[$field])->select();
        $row->isEmpty() && $this->error('数据不存在');
        try {
            $save = $row->delete();
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    /**
     * @NodeAnotation(title="导出")
     */
    public function export()
    {
//        list($page, $limit, $where) = $this->buildTableParames();
        $where = Cache::get('where'.__CLASS__);
        $tableName = $this->model->getName();
        $tableName = CommonTool::humpToLine(lcfirst($tableName));
//        $prefix = config('database.connections.mysql.prefix');
        if(empty($this->AllData['field'])){
            $dbList = Db::name('system_field')
                ->where('status',1)
                ->where('table',$tableName)
                ->order('sort desc')
                ->select()->toArray();
            $dbListKey = array_column($dbList,'field');
            $dbList = array_combine($dbListKey,$dbList);
        }else{
            $dbList = $this->AllData['field'];
        }
//        $header = [];
//        foreach ($dbList as $vo){
//            if($vo['export']==1){
//                $header[] = [$vo['name']??$vo['field'],$vo['field']];
//            }
//        }
        $list = $this->model
            ->where($where)
            ->limit(100000)
            ->order('id', 'desc')
            ->select()
            ->toArray();
        list($list,$header) = PublicUse::exportObjctToModelAndField($list,$dbList);
//        echo '<pre>';
//        print_r($list);
//        print_r($header);
//        exit;
        $fileName = time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }

    /**
     * @NodeAnotation(title="属性修改")
     */
    public function modify()
    {
        $post = $this->request->post();
        $rule = [
            'id|ID'    => 'require',
            'field|字段' => 'require',
            'value|值'  => 'require',
        ];
        $this->validate($post, $rule);
        $row = $this->model->find($post['id']);
        if (!$row) {
            $this->error('数据不存在');
        }
        if (!in_array($post['field'], $this->allowModifyFields)) {
            $this->error('该字段不允许修改：' . $post['field']);
        }
        try {
            $row->save([
                $post['field'] => $post['value'],
            ]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('保存成功');
    }

}
